package net.mihome.app.ui;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import net.mihome.app.AppContext;
import net.mihome.app.R;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Created by ZHAO on 2014/12/29 0029.
 */
public class MifuwuFragment extends Fragment {
    static MifuwuFragment instance;
    private ViewPager viewPager;
    private ScheduledExecutorService scheduledExecutorService;
    private int currentItem = 0;//当前页面
    private Handler handler;
    private Timer timer;
    private ImageLoader imageLoader;
    MyAdapter adapter;
    /**
     * 装ImageView数组
     */
    private ImageView[] mImageViews;
    private List<String> imgIdArray ;//广告图片资源

    /**
     * 装点点的ImageView数组
     */
    private ImageView[] tips;
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mainView = inflater.inflate(R.layout.frame_question, null, false);
        imageLoader=ImageLoader.getInstance();
        viewPager= (ViewPager) mainView.findViewById(R.id.mihome_viewpager);
        ViewGroup group = (ViewGroup)mainView.findViewById(R.id.viewGroup);
        //将图片装载到数组中
        User user= AppContext.getInstance().getLoginInfo();
        imgIdArray=new ArrayList<>();
        imgIdArray.add(URLs.MIHOME_COMMUNITY_SNAPSHOT_VIEW+"?order_num=1&token="+user.getToken()+"");
        imgIdArray.add(URLs.MIHOME_COMMUNITY_SNAPSHOT_VIEW+"?order_num=2&token="+user.getToken()+"");
        imgIdArray.add(URLs.MIHOME_COMMUNITY_SNAPSHOT_VIEW+"?order_num=3&token="+user.getToken()+"");
        imgIdArray.add(URLs.MIHOME_COMMUNITY_SNAPSHOT_VIEW+"?order_num=4&token="+user.getToken()+"");
        imgIdArray.add(URLs.MIHOME_COMMUNITY_SNAPSHOT_VIEW+"?order_num=5&token="+user.getToken()+"");

        //将点点加入到ViewGroup中
        tips = new ImageView[imgIdArray.size()];
        for(int i=0; i<tips.length; i++){
            ImageView imageView = new ImageView(getActivity());
            imageView.setLayoutParams(new LayoutParams(10,10));
            tips[i] = imageView;
            if(i == 0){
                tips[i].setBackgroundResource(R.drawable.page_indicator_focused);
            }else{
                tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);
            }

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 5;
            layoutParams.rightMargin = 5;
            group.addView(imageView, layoutParams);
        }
        mImageViews = new ImageView[imgIdArray.size()];
        for(int i=0; i<mImageViews.length; i++){
            ImageView imageView = new ImageView(getActivity());
            mImageViews[i] = imageView;
//            imageView.setBackgroundResource(imgIdArray[i]);
            imageLoader.displayImage(imgIdArray.get(i),mImageViews[i],options);
        }
        //设置Adapter

        adapter=new MyAdapter();
        viewPager.setAdapter(adapter);
        //设置监听，主要是设置点点的背景
        viewPager.setOnPageChangeListener(onPageChangeListener);
        //设置ViewPager的默认项, 设置为长度的100倍，这样子开始就能往左滑动
        viewPager.setCurrentItem((mImageViews.length) * 100);
        handler=new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                viewPager.setCurrentItem(message.what);
                return false;
            }
        });
        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                int currentIndex = viewPager.getCurrentItem();
                currentIndex++;
                handler.sendEmptyMessage(currentIndex);
            }
        }, 2000, 3000);
        return mainView;
    }
    public static MifuwuFragment newInstance(){
        if(instance==null){
            instance=new MifuwuFragment();
        }
        return instance;
    }
    /**
     *
     * @author xiaanming
     *
     */
    public class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView(mImageViews[position % mImageViews.length]);

        }

        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView(mImageViews[position % mImageViews.length], 0);
            return mImageViews[position % mImageViews.length];
        }
    }
    /**
     * viewpager change
     * */
    public ViewPager.OnPageChangeListener onPageChangeListener= new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            currentItem = position;
            setImageBackground(position % mImageViews.length);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };
    /**
     * 设置选中的tip的背景
     * @param selectItems
     */
    private void setImageBackground(int selectItems){
        for(int i=0; i<tips.length; i++){
            if(i == selectItems){
                tips[i].setBackgroundResource(R.drawable.page_indicator_focused);
            }else{
                tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);
            }
        }
    }
    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.drawable.focus_1)
            .showImageForEmptyUri(R.drawable.focus_1) // resource or drawable
            .showImageOnFail(R.drawable.focus_1) // resource or drawable
            .resetViewBeforeLoading(false)  // default
            .cacheInMemory(true) // default
            .cacheOnDisk(false) // default
            .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
            .bitmapConfig(Bitmap.Config.ARGB_8888) // default
            .displayer(new SimpleBitmapDisplayer()) // default
            .handler(new Handler()) // default
            .build();
}
